package org.ucas.faker.web.entity.patents;

import org.ucas.faker.web.utils.model.RawPatent;
import org.ucas.faker.web.service.PatentService;

import java.util.ArrayList;
import java.util.List;

public class PatentWrapper implements Patentable {

  public static PatentService service;

  private Long id;

  private PatentMeta meta;

  private PatentContent content;

  private Patent patent;

  private PatentFeature feature;

  private List<Agency> agencies;

  private List<Symbol> symbols;

  public PatentWrapper(long id) {
    this.id = id;
  }

  public void writeBack() {
    if(feature != null) {
      feature.setId(id);
      service.persistFeature(feature);
    }
  }

  public RawPatent toRaw() {
    if(id == null) return null;
    if(meta == null) meta = service.loadMeta(id);
    if(content == null) content = service.loadContent(id);
    if(patent == null) patent = service.load(id);
    if(agencies == null) agencies = service.loadAgencies(id);
    if(symbols == null) symbols = service.loadSymbols(id);

    RawPatent res = new RawPatent();
    
    if(meta!=null) meta.to(res,true);
    if(patent!=null) patent.to(res,true);
    if(content!=null) content.to(res,true);
    if(feature!=null) feature.to(res,true);
    if(agencies!=null) for(Agency agency:agencies) agency.to(res,true);
    if(symbols!=null) for(Symbol symbol:symbols) symbol.to(res,true);
    return res;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public PatentMeta getMeta() {
    if(meta == null) meta = service.loadMeta(id);
    return meta;
  }

  public void setMeta(PatentMeta meta) {
    this.meta = meta;
  }

  public PatentContent getContent() {
    if(content == null) content = service.loadContent(id);
    return content;
  }

  public void setContent(PatentContent content) {
    this.content = content;
  }

  public Patent getPatent() {
    if(patent == null) patent = service.load(id);
    return patent;
  }

  public void setPatent(Patent patent) {
    this.patent = patent;
  }

  public PatentFeature getFeature() {
    if(feature == null) feature = service.loadFeature(id);
    return feature;
  }

  public void setFeature(PatentFeature feature) {
    this.feature = feature;
  }

  public void of(RawPatent patent, boolean overwrite) {
    this.id = patent.id;
    meta.of(patent,overwrite);
    feature.of(patent,overwrite);
    content.of(patent,overwrite);
    this.patent.of(patent,overwrite);

    this.agencies = patent.agencies();
    this.symbols = patent.symbols();
  }

  public void to(RawPatent patent, boolean overwrite) {
    patent.id = this.id;
    meta.to(patent,overwrite);
    this.patent.to(patent,overwrite);
    content.to(patent,overwrite);
    feature.to(patent,overwrite);

    for(Agency agency:agencies) agency.to(patent,overwrite);
    for(Symbol symbol:symbols) symbol.to(patent,overwrite);
  }
}
